package com.itheima.filter;

import com.itheima.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      // 是所有的请求都要拦截吗   /login
      //   获取当前请求的url
        HttpServletRequest request  = (HttpServletRequest) servletRequest;
        HttpServletResponse response  = (HttpServletResponse) servletResponse;
        if (request.getRequestURI().contains("/login")) {
            // 放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        // 拦截的情况：1 没有token  2、判断token是否合法
        String token = request.getHeader("token");
        if(token==null){
            response.setStatus(401);
            return;
        }

        try {
            JwtUtils.parseJWT(token);
            // 放行
            filterChain.doFilter(servletRequest,servletResponse);
        } catch (Exception e) {
            response.setStatus(401);
            return;
        }
    }

}
